<?php

namespace app\api\controller;

use app\api\exception\AppletIdException;
use app\api\exception\TokenException;
use app\api\service\TokenService;
use think\Controller;
use think\Exception;
use think\Request;

class Base extends Controller
{
    protected $appletId;
    protected $userId;
    protected $openId;
    protected $token;

    /**
     * 检测用户的令牌是否过期
     * @throws Exception
     * @author 清凉Tea <973110519@qq.com>
     */
    protected function checkToken()
    {
        $this->appletId = Request::instance()->header('appletId');
        if(!$this->appletId){
            throw new Exception('AppletId 不能为空',401);
        }
        $token = Request::instance()->header('token');
        $tokenService = new TokenService();
        if(!$tokenService->check($token)){
            throw new TokenException();
        }
        $this->userId = $tokenService->userId;
        $this->openId = $tokenService->openId;
        $this->token = $token;
    }

    /**
     * 处理返回Json 数据
     * @param $data
     * @param int $code
     * @param string $msg
     * @return \think\response\Json
     * @author 清凉Tea <973110519@qq.com>
     */
    public static function apiResp($data,$code=200)
    {
        if(isset($data['_code'])){
            $code = $data['_code'];
            unset($data['_code']);
        }
        if(strpos($code,'2') === 0 && !empty($data)){
            $res['status'] = 0;
            $res['msg'] = '成功';
        }else{
            $res['status'] = -1;
            $res['msg'] = '失败';
        }
        $res = array_merge($res,$data);
        return json($res,$code);
    }
}
